<?php

namespace Plugin\BatchPrice\Controllers;

use Beike\Models\ProductSku;
use Beike\Shop\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ProductPriceController extends Controller
{
    public function batch(Request $request)
    {
        $value1 = $request['value1'];
        $value2 = $request['value2'];
        if (!is_numeric($value1) && !is_numeric($value2)) {
            return json_success("金额必须为数值");
        }
        // 查询所有选中的产品
        $products = ProductSku::whereIn('product_id', $request['ids'])->get();
        // 批量更新价格
        foreach ($products as $product) {
            //按现有价格修改
            if ($request['selectType'] == 1) {
                $excType = $request['excType'];
                //百分比
                if ($excType == 'percent') {
                    $priceAdjustment = $product->price * (1 + $value1 / 100);
                }
                //金额
                if ($excType == 'amount') {
                    $priceAdjustment = $value1;
                }
                if ($priceAdjustment > 0) {
                    // 正数：增加价格
                    $product->increment('price', $priceAdjustment);
                } else {
                    // 负数：减少价格（使用绝对值）
                    $product->decrement('price', abs($priceAdjustment));
                }
            }
            //直接修改
            if ($request['selectType'] == 2) {
                $product->update(['price' => abs($value2)]);
            }
        }
        return json_success("修改成功");
    }
}
